__author__ = 'guo'

from  extends.BaseHandle import BaseHandle
from bson.objectid import ObjectId
import tornado.web
import time
import hashlib



# 用户中心
class User(BaseHandle):

    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        # cate = self.db.catelog.find()
        pageNum = self.get_argument("pageNum", 1)
        pageNum = int(pageNum)

        data = self.pagination(pageNum)

        articlelist = []
        if data['article'] is not None:
            articlelist = self.Conver(data['article'])
        return self.render("article/list.html", articlelist=articlelist, pageNum=pageNum, pagination=data['pagination'])



# 修改用户个人资料
class UserEdit(BaseHandle):
    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        return self.render("profile.html", message="", userinfo=self.get_current_user())

    @tornado.web.authenticated
    def post(self, *args, **kwargs):
        uid = self.get_argument("uid", '')
        uname = self.get_argument("uname", '')
        email = self.get_argument("email", "")
        paswd = self.get_argument("paswd", '')
        mobile = self.get_argument("mobile", '')
        gender = self.get_argument("gender", '')#暂无
        avatar = self.get_argument("avatar", '') #这个地方要改成file  查tornado上传文件手册
        description = self.get_argument("description", '')
        birthday = self.get_argument("birthday", '')#暂无
        age = self.get_argument("age", '')#暂无
        website = self.get_argument("user_website", '')
        qqweibo = self.get_argument("qq_weibo", '')
        sinaweibo = self.get_argument("sina_weibo", '')
        google_plus = self.get_argument("google_plus", '')
        twitter = self.get_argument("twitter", '')

        if uid is None:
            self.redirect(self.get_argument("next", "/"))
        info = {
                # "uname": uname,
                "email": email,
                "password": self.HashPwd(paswd),
                "mobile": self.TripString(mobile),
                "gender": self.TripString(gender),
                "avatar": self.TripString(avatar),
                "description": self.TripString(description),
                "age": self.TripString(age),
                "birthday": self.TripString(birthday),
                "website": self.TripString(website),
                "qqweibo": self.TripString(qqweibo),
                "sinaweibo": self.TripString(sinaweibo),
                "google_plus": self.TripString(google_plus),
                "twitter": self.TripString(twitter),
                "update": time.time(),
            }
        if not self.TripString(paswd):
            del info['password']
        self.db.user.update({"_id": ObjectId(uid)}, {"$set": info})
        return self.render("profile.html", message="更新成功", userinfo=self.get_current_user())


# 用户登录
class UserLogin(BaseHandle):
    def get(self, *args, **kwargs):
        self.render("login.html", message="")

    def post(self, *args, **kwargs):
        uname = self.get_argument("uname", None)
        paswd = self.get_argument("paswd", None)

        if self.checkType(uname) == "EMAIL":
            userinfo = self.db.user.find_one({"email": uname})
        else:
            userinfo = self.db.user.find_one({"uname": uname})

        if userinfo is None:
            return self.render("login.html", message="此用名或邮箱未注册")
        else:
            password = hashlib.md5(paswd.strip().encode("utf8")).hexdigest()
            if password != userinfo["password"].strip():
                return self.render("login.html", message="用户名或密码不正确")
            self.set_current_user(uname)

            # self.set_secure_cookie("uid", str(ObjectId(userinfo["_id"])))
            # self.set_secure_cookie("uname", userinfo["uname"])
            # self.set_secure_cookie("email", userinfo["email"])
            print(self.get_argument("next", "/"))
            self.redirect(self.get_argument("next", "/"))

#用户退出
class UserLogout(BaseHandle):
    def get(self, *args, **kwargs):
        self.clear_cookie("userinfo")
        self.redirect(self.get_argument("next", "/"))



# 用户注册
class UserReg(BaseHandle):
    def check_origin(self, origin):
        return True

    def get(self, *args, **kwargs):
        message = self.get_argument("message", None)
        return self.render("register.html", message=message)

    # @gen.coroutine
    def post(self, *args, **kwargs):
        uname = self.get_argument("uname", None)
        email = self.get_argument("email", None)
        paswd = self.get_argument("paswd", None)
        dpaswd = self.get_argument("dpaswd", None)
        xsrf = self.get_argument("xsrf", None)

        if paswd.strip() != dpaswd.strip():
            return self.render("register.html", message="两次密码输入不一致")
        if self.checkType(email) != "EMAIL":
            return self.render("register.html", message="邮箱格式不正确")

        # userCount = self.db.user.find({"$or": [{"uname": uname}, {"email": email}]}).count()
        userCount = self.db.user.find({"uname": uname.strip()}).count()
        emailCount = self.db.user.find({"email": email.strip()}).count()

        if userCount > 0:
            message = "此用户名已被注册"
            return self.render("register.html", message=message)

        if emailCount > 0:
            message = "此邮箱名已被注册"
            return self.render("register.html", message=message)

        affectedRows = self.db.user.insert(
                {
                    "uname": uname,
                    "email": email,
                    "password": self.HashPwd(paswd),
                    "create": time.time(),
                    "avatar": "",
                    "ver_authorcontent": {},
                    "description": "",
                    "type": "",
                }
        )
        return self.redirect("/user/login/")



# 新建文章
class UserPost(BaseHandle):
    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        if not self.current_user:
            return self.redirect("/user/login")
        cate = self.db.catelog.find()

        action = self.get_argument('action', '')
        if action == 'edit':
            pid = self.get_argument('pid', 0)
            if pid == 0:
                print("非法操作")
            articleInfo = self.db.article.find_one({"_id": ObjectId(pid)})
            return self.render("post-new.html", message="", article=articleInfo, ObjectId=ObjectId, type='edit')
        elif action == 'del':
            return "删除操作"
        else:
            return self.render("post-new.html", message="", article='')

    @tornado.web.authenticated
    def post(self, *args, **kwargs):

        if not self.current_user:
            return self.redirect("/user/login")

        title = self.get_argument("post_title", '')
        category = self.get_argument("category", None)
        content = self.get_argument("post_content", None)
        img = self.get_argument("img", None)


        userinfo = self.get_current_user()
        cate = self.db.catelog.find()

        if title == '' or content == '':
            return self.render("post-new.html", message="标题和内容不能为空", article='')

        titleRows = self.db.article.find({"title": title, "uid": userinfo["_id"]}).count()

        if category == '-1':
            return self.render("post-new.html", message="请选择栏目", article='')

        if titleRows > 0:
            return self.render("post-new.html", message="您已经发表过此标题的文章", article='')


        cname = self.db.catelog.find_one({'_id': ObjectId(category)})
        action = self.get_argument('action', 'No')
        if action == 'new':
            reffected = self.db.article.insert(
                {
                    "title": title,
                    "img": img,
                    "content": content,
                    "cid": category,
                    "cname": cname['name'],
                    "create": time.time(),
                    "author": userinfo["uname"],
                    "author_id": userinfo["_id"],
                    "author_name": userinfo["uname"],
                    "looks": 0,
                    "comment": []
                 },
            )
        elif action == 'edit':
            pid = self.get_argument('pid', '')
            reffected = self.db.article.update(
                {"_id": ObjectId(pid)},
                {'$set':
                    {
                        "title": title,
                        "content": content,
                        "cid": category,
                        "cname": cname['name'],
                        "update": time.time(),
                     }
                 }
            )
            # self.db.article.update({"_id": ObjectId(id)}, {'$set': {'cname': catelog['name']}}, upsert=True)
        return self.redirect("/user")


# 文章收藏
class UserFavorites(BaseHandle):
    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        favorites = self.db.favorites.find({'uid': self.get_current_user()['_id']}).count()
        favoritelist = []
        if favorites is not 0:
            favoritelist = self.Conver(self.db.favorites.find())
        return self.render("favorite.html", favoritelist=favoritelist)

    def post(self, *args, **kwargs):
        action = self.get_argument('wpfpaction', None)

        favoriteJson = {}
        favoriteJson['code'] = 120
        favoriteJson['message'] = "未登录,请登录后再收藏"

        if not self.current_user:
            return self.api_response(favoriteJson)

        postid = self.get_argument("postid", None)
        userinfo = self.get_current_user()
        ArticleInfo = self.db.article.find_one({"_id": ObjectId(postid)})

        if postid is not None:
            if action == "add":
                FavoritesInfo = self.db.Favorites.find_one({"pid": ObjectId(postid)})
                if FavoritesInfo != None:
                    favoriteJson['code'] = 200
                    favoriteJson['message'] = "您已经收藏过这篇文章"
                else:
                    self.db.favorites.insert(
                                            {
                                                "pid": postid,
                                                "title": ArticleInfo['title'],
                                                "uid": userinfo["_id"]
                                            }
                    )
                    favoriteJson['code'] = 200
                    favoriteJson['message'] = "收藏成功"
            elif action == 'remove':
                self.db.favorites.remove({"pid": postid})
                favoriteJson['code'] = 200
                favoriteJson['message'] = "删除成功"
        else:
            favoriteJson['code'] = 110
            favoriteJson['message'] = '非法操作'
        return self.api_response(favoriteJson)






